import React, {PropTypes} from 'react'
import {connect} from 'dva'
import {hashHistory} from 'dva/router'
import {Form, Input, Select, Button, Row, Col, Icon, Modal, Spin, Collapse } from 'antd'
import {FileUpload, PageLabel, BoxLabel} from '../../components/cor'
import '../../components/cor/cms.less'
const FormItem = Form.Item;
const Panel = Collapse.Panel;

function configColumAdd({location, dispatch, form, configColumAdd}) {
  if (!configColumAdd) {
    return null;
  }
  const {columnConfigId, detailLoading,columnConfig, columnConfigName} = configColumAdd;
  const {getFieldDecorator, validateFields, getFieldsValue} = form;
  const actionTypeHead = 'configColumAdd/';
  const pageLabelProps = {
    isCorTable: true,
    current: columnConfigName + '的配置信息',
  };
  // 获取提交参数进行二次处理数据
  const getParams=(data) =>{
    var datas = columnConfig;
    for(var i in data){
      var param = i.split('-');
      if(param.length==2){
        if(param[0] != "url"){
          datas[param[1]][param[0]] = data[i]
        } else {
          datas[param[1]].buttons[0].action = data[i]
        }
      } else{
        datas[param[1]].tableHeads[param[2]][param[0]] = data[i]
      }
    }
    var dataArr = datas.map(function (value) {
      if(value.type=='2'){
        delete value.tableHeads;
      };
      return value;
    });
    return dataArr
  };
  const submitHandle = () => {
    validateFields((errors) => {
      if (errors) {
        return
      }
      const data = {...getFieldsValue()};
      var dataParam = {
        id:columnConfigId ? columnConfigId:null,
        components:getParams(data)
      };

      dispatch({
        type: `${actionTypeHead}add`,
        payload: {
          ...dataParam
        }
      })
    })
  };
  const addFilter = (index,idx,type) => {
    dispatch({
      type: `${actionTypeHead}managerTableItem`,
      payload: {
        index:index,
        idx : idx,
        type: type
      }
    });
  };
  const handleType= (index,value )=>{
    dispatch({
      type: `${actionTypeHead}handleType`,
      payload: {
        index:index,
        type: value
      }
    });
  };
  const itemHandle = (type,index) =>{
    dispatch({
      type: `${actionTypeHead}itemHandle`,
      payload: {
        type:type,
        index:index
      }
    });
  };
  // 取消编辑
  const cancelHandle = () => {
    Modal.confirm({
      title: '确定放弃编辑数据?',
      content: null,
      onOk() {
        hashHistory.goBack();
      },
      onCancel() {
      },
    });
  };
  // 表单头动态生成
  const templates = ()=>{
    return columnConfig.length == 0 ? <div className="noData">暂无配置</div> : columnConfig.map((value,index)=>{
      return (
        <div key={index}   className="colmusAdd">
          <div className="close" onClick={itemHandle.bind(this,'delete',index)}>X</div>
          <Row gutter={16} style={{marginTop: "22px"}}>
            <Col className="gutter-row" span={6}>
              <FormItem {...formItemLayout} label="名 称 ：">
                {getFieldDecorator('title-'+ index, (value !== null && value.title) ? {initialValue: value.title + ''} : null)(<Input placeholder="请输入名称 "/>)}
              </FormItem>
            </Col>
            <Col className="gutter-row" span={6}>
              <FormItem {...formItemLayout} label="字 段 ：">
                {getFieldDecorator('inputFiled-' + index,(value !== null && value.inputFiled) ? {initialValue: value.inputFiled + ''} : null)(<Input placeholder="请输入字段 "/>)}
              </FormItem>
            </Col>
            <Col className="gutter-row" span={6}>
              <FormItem {...formItemLayout} label="图片字段 ：">
                {getFieldDecorator('imgField-' + index,(value !== null && value.imgField) ? {
                  initialValue: value.imgField + '',
                } : null)(<Input placeholder="请输入图片字段 "/>)}
              </FormItem>
            </Col>
            <Col className="gutter-row" span={6}>
              <FormItem {...formItemLayout} label="类型 :">
                {getFieldDecorator('type-' + index,(value !== null && value.type) ? {
                  initialValue: value.type + '',
                } : null)(
                  <Select allowClear multiple={false} onSelect={handleType.bind(this,index)} style={{width: '100%'}} placeholder="请选择类型">
                    <Select.Option value="1">list</Select.Option>
                    <Select.Option value="2">pic</Select.Option>
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <div style={{display:value.type=="1" ? 'block':'none'}}>
          <BoxLabel text="list类型的列表表头"/>
          <Row gutter={16}>
            <Col className="gutter-row" span={10}>
              <FormItem {...formItem} label="接口：">
                {getFieldDecorator('url-' + index,(value !== null && value.buttons) ? {
                  initialValue: value.buttons[0].action + '',
                } : null)(<Input placeholder="请输入接口 "/>)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={16}>
              <Row gutter={16} justify="center"  style={{marginBottom : "11px"}}>
                <Col className="gutter-row" span={10}>
                  <label>名称</label>
                </Col>
                <Col className="gutter-row" span={10}>
                  <label>字段</label>
                </Col>
                <Col className="gutter-row" push={1} span={3}>
                  <label>操作</label>
                </Col>
              </Row>
          </Row>
            {value.tableHeads ? value.tableHeads.map((val,idx)=>{
              return (<div key={idx}>
                <Row gutter={16}>
                  <Col className="gutter-row" span={10}>
                    <FormItem hasFeedback>{getFieldDecorator('displayName-'+ index + "-" + idx, {initialValue: (val && val.displayName) || '', rules: [{required: true, message: '描述'}],})(<Input  placeholder="请输入描述"/>)}</FormItem>
                  </Col>
                  <Col className="gutter-row" span={10}>
                    <FormItem hasFeedback>{getFieldDecorator('fieldName-'+ index +"-"+idx, {initialValue: (val && val.fieldName) || '', rules: [{required: true, message: '字段'}],})(<Input placeholder="请输入字段"/>)}</FormItem>
                  </Col>
                  <Col className="gutter-row" span={4}>
                    <FormItem hasFeedback><span style={{fontSize: "20px",marginLeft: "40px"}} onClick={addFilter.bind(this, index, idx ,'add')}><Icon style={{color:'white'}} type="plus-circle-o" /></span><span style={{fontSize: "20px",marginLeft: "20px"}} onClick={addFilter.bind(this,index, idx ,'delete')}><Icon style={{color:'white'}} type="delete"/></span></FormItem>
                  </Col>
                </Row>
              </div>)
            }):""}
          </div>
        </div>
      )
    })
  };
  const formItemLayout = {
    labelCol: {
      xs: { span: 4 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 20 },
      sm: { span: 20 },
    },
  };
  const formItem = {
    labelCol: {
      xs: { span: 2 },
      sm: { span: 2 },
    },
    wrapperCol: {
      xs: { span: 22 },
      sm: { span: 22 },
    },
  };
  return (
    <div className="content-inner">
        <Row className="marginB16 bgcWhite">
          <PageLabel {...pageLabelProps} />
          <div className="noTopBorder">
            <div className="tabContent">
              <Form layout="horizontal">
                {templates()}
              </Form>
              <div style={{paddingTop: '24px'}}>
                <Button size={'large'} style={{marginRight: '20px'}} onClick={cancelHandle}>取消</Button>
                <Button size={'large'} type="primary" style={{marginRight: '20px'}} onClick={submitHandle}>保存</Button>
                <Button size={'large'} onClick={itemHandle.bind(this,'add',"-1")} type="danger" >新增模块</Button>
              </div>
            </div>
          </div>
        </Row>
    </div>
  )
}

function mapStateToProps({configColumAdd}) {
    return {configColumAdd}
}

export default Form.create({})(connect(mapStateToProps)(configColumAdd))
